# dest.py: Receives UDP packets and sends them back
import sys
import threading
import time
import socket
from optparse import OptionParser

class Dest():
  def __init__(self, dest_addr, dest_port, local_port):
    self.dest = (dest_addr, dest_port)
    self.local = ('0.0.0.0', local_port)
    self.listen_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    self.listen_sock.bind(self.local)
    self.outgoing_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    self.thread = threading.Thread(target=self.runner_thread)
    self.avg_rtt = None
    self.thread.daemon = True
    self.loop = 0
    
  def runner_thread(self):
    # Using a runner thread so we can ctrl + c out of the program
    while True:
      data, addr = self.listen_sock.recvfrom(1024)
      if len(data.split(' ')) == 2:
        data, addr_colon = data.split(' ')
        addr = addr_colon.split(':')
      host, port = addr
      print 'recv %f %s' % (time.time(), data)
      self.outgoing_sock.sendto(data, (host, int(port)))    
      print 'send %f %s to %s:%s' % (time.time(), data, host, port)
    
  def run(self):
    self.thread.start()
    while True:
      time.sleep(1)
    

if __name__ == '__main__':
  # Parse arguments [dest_addr=localhost] [dest_port=9003] [local_port=9002]
  parser = OptionParser()
  parser.add_option("-d", "--dest_addr", dest="dest_addr", default='127.0.0.1',
                    help="Destination IP address")
  parser.add_option("-p", "--dest_port", dest="dest_port", default=9003, type='int',
                    help="Destination port number")
  parser.add_option("-l", "--local_port", dest="local_port", default=9002, type='int',
                    help="Local (listening) port number")
  (options, args) = parser.parse_args()
  
  # Create a new "Source" object
  print 'Binding to port %d...' % options.local_port
  dest = Dest(options.dest_addr, options.dest_port, options.local_port)
  
  # Run forever
  print 'Running...'
  dest.run()